package com.jeesite.modules.dataScreen.spi;


import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.*;
import com.jeesite.modules.dataScreen.web.vo.IndustryIndexVo;
import lombok.Getter;

import java.util.*;

public class IndustryCollection {

    private static final String DECOLLATOR = "$as";
    static TimedCache<IndustryCollection, wrap> cacheData = CacheUtil.newTimedCache(10 * 1000);

    private final String jsonPath;

    public static IndustryCollection of(String jsonPath) {
        return new IndustryCollection(jsonPath);
    }

    private IndustryCollection(String jsonPath) {
        this.jsonPath = jsonPath;
    }

    /**
     * 获取查询数据库时的指标，包含json文件中sums对象指标名称
     */
    public String[] getSelectNames() {
        wrap wrap = getWrap();
        ListMultimap<String, String> multimap = wrap.getMultimap();
        String[] array = wrap.getData().values().toArray(new String[0]);
        if (multimap.isEmpty()) {
            return array;
        }
        return ArrayUtil.addAll(array, multimap.values().toArray(new String[0]));
    }

    /**
     * 获取指定子模块的指标名称(不包含sums数据)
     *
     * @param keys 模块名称
     * @return 指标名称
     */
    public String[] getNameByKeys(String... keys) {
        ListMultimap<String, String> data = getData();
        List<String> values = new ArrayList<>();
        for (String key : keys) {
            values.addAll(data.get(key));
        }
        if (keys.length == 0) {
            values.addAll(data.values());
        }
        return values.toArray(new String[0]);
    }

    public ListMultimap<String, String> getData() {
        return getWrap().getData();
    }

    public ListMultimap<String, String> getMultimap() {
        return getWrap().getMultimap();
    }

    public void transferNames(Collection<IndustryIndexVo> indexVos) {
        Map<String, String> biMap = getWrap().getBiMap();
        String name;
        for (IndustryIndexVo indexVo : indexVos) {
            if (StrUtil.isNotBlank(name = biMap.get(indexVo.getIndicatorName()))) {
                indexVo.setIndicatorName(name);
            }
        }
    }

    public void sumHandler(Map<String, IndustryIndexVo> indexVoMap) {
        if (CollUtil.isEmpty(indexVoMap) || getMultimap().isEmpty()) {
            return;
        }
        Map<String, Collection<String>> collectionMap = getMultimap().asMap();
        for (Map.Entry<String, Collection<String>> entry : collectionMap.entrySet()) {
            String entryKey = entry.getKey();
            IndustryIndexVo indexVo = indexVoMap.get(entryKey);
            if (indexVo == null) {
                indexVo = new IndustryIndexVo();
                indexVo.setIndicatorName(entryKey);
            }
            indexVo.setIndicatorValue(IndustryIndexVo.addAll(indexVoMap, entry.getValue()).toString());
            indexVoMap.put(entryKey, indexVo);
        }
    }

    private wrap getWrap() {
        return cacheData.get(this, () -> {
            Map<String, String> biMap = new HashMap<>();
            JSONObject jsonObject = IndustryNameLoader.load(jsonPath);
            //模块对应指标名称
            ListMultimap<String, String> moduleMap = ArrayListMultimap.create();
            //指标求和对应的指标集合
            ListMultimap<String, String> multimap = ArrayListMultimap.create();
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                String key = entry.getKey();
                JSONArray jsonArray = (JSONArray) entry.getValue();
                List<String> vals = new ArrayList<>();
                for (Object object : jsonArray) {
                    if (object instanceof String) {
                        String[] split = split(object.toString());
                        if (split != null && split.length == 2) {
                            //设置别名
                            biMap.put(split[0], split[1]);
                            vals.add(split[0]);
                        } else {
                            vals.add(object.toString());
                        }
                    }
                    if (object instanceof JSONObject) {
                        JSONObject json = (JSONObject) object;
                        String name = json.getString("name");
                        vals.add(name);
                        String alias = json.getString("alias");
                        if (StrUtil.isNotBlank(alias)) {
                            biMap.put(name, alias);
                        }
                        JSONArray sums = json.getJSONArray("sums");
                        if (sums != null && !sums.isEmpty()) {
                            multimap.putAll(name, sums.toJavaList(String.class));
                        }

                    }
                }
                moduleMap.putAll(key, vals);
            }
            return new wrap(moduleMap, biMap, multimap);
        });
    }


    @Getter
    static class wrap {
        //子模块名对应指标数据
        private final ListMultimap<String, String> data;
        //别名数据
        private final Map<String, String> biMap;
        //求和指标名称集合
        private final ListMultimap<String, String> multimap;

        wrap(ListMultimap<String, String> data, Map<String, String> biMap, ListMultimap<String, String> multimap) {
            this.data = data;
            this.biMap = biMap;
            this.multimap = multimap;
        }
    }

    private String[] split(String val) {
        if (StrUtil.isNotBlank(val)) {
            List<String> split = StrUtil.split(val, DECOLLATOR, true, true);
            if (split.size() == 2) {
                return split.toArray(new String[0]);
            }
        }
        return null;
    }
}
